﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.CBO.HR.Department;
using UFIDA.U9.Cust.YYD.PlugBE.Dtos;

namespace UFIDA.U9.Cust.YYD.PlugBE.Public
{
    public class HttpHelper
    {
        public string URL { get; set; }
        public string Content { get; set; }
        public Dictionary<string, string> Header { get; set; } = new Dictionary<string, string>();
        public string ContentType { get; set; } = "application/json";
        public string Request(string postType = "POST")
        {

            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"请求地址:{URL}");

            var request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = postType;
            request.ContentType = ContentType;//ContentType

            foreach (var item in Header)
            {
                request.Headers.Add(item.Key, item.Value);
            }
            if (postType != "GET")
            {
                sb.AppendLine("请求参数:" + Content);
                byte[] byteData = Encoding.UTF8.GetBytes(Content);
                int length = byteData.Length;
                request.ContentLength = length;
                Stream writer = request.GetRequestStream();
                writer.Write(byteData, 0, length);
                writer.Close();
            }

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
                sb.AppendLine($"返回值:{responseString}");
                LogManager.WriteLog(sb.ToString(), "AllRequest");
                return responseString;
            }
            catch (Exception e)
            {
                sb.AppendLine($"{e.Message}\r\n{e.StackTrace}");
                LogManager.WriteLog(sb.ToString(), "All");
                throw new Exception(e.Message);
            }
        }


        public string HttpPosts(string postType = "POST")
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"请求地址:{URL}");
            string rtn = string.Empty;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);

            if (URL.StartsWith("https"))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
                                           | SecurityProtocolType.Tls
                                           | SecurityProtocolType.Tls11
                                           | SecurityProtocolType.Tls12;
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
            }
            httpWebRequest.ProtocolVersion = HttpVersion.Version10;
            //httpWebRequest.Proxy = new WebProxy(url, false); // 根据实际代理地址修改
            httpWebRequest.ServicePoint.Expect100Continue = false;
            httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)";
            httpWebRequest.Accept = "*/*";

            httpWebRequest.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");


            foreach (var item in Header)
            {
                httpWebRequest.Headers.Add(item.Key, item.Value);
            }
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = postType;
            httpWebRequest.Timeout = 20000;
            byte[] btBodys = Encoding.UTF8.GetBytes(Content);
            httpWebRequest.ContentLength = (long)btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
            HttpWebResponse httpWebResponse;
            try
            {
                sb.AppendLine("请求参数:" + Content);
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpWebResponse = (HttpWebResponse)ex.Response;
                LogManager.Error(ex);

            }
            bool flag = httpWebResponse != null;
            if (flag)
            {
                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
                string responseContent = streamReader.ReadToEnd();
                sb.AppendLine($"返回值:{responseContent}");
                rtn = responseContent;
                httpWebResponse.Close();
                streamReader.Close();
                httpWebRequest.Abort();
                httpWebResponse.Close();
                LogManager.WriteLog(sb.ToString(), "AllRequest");
            }

            return rtn;
        }

        public void GetMESToken()
        {
            JsonConfig config = new JsonConfig();
            HttpHelper httpHelper = new HttpHelper();
            httpHelper.URL = config.SelectToken("MES.URL") + "/auth/login";
            var body = new
            {
                username = config.SelectToken("MES.username"),
                password = config.SelectToken("MES.password"),
                tenant = config.SelectToken("MES.tenant")
            };
            httpHelper.Content = JsonConvert.SerializeObject(body);
            var result = JObject.Parse(httpHelper.Request("PUT"));
            if (!string.IsNullOrEmpty(result["authToken"]?.ToString()))
            {
                string token = $"Authorization={result["authToken"]}";
                if (this.Header.ContainsKey("Cookie"))
                {
                    this.Header["Cookie"] = token;
                    //this.Header["Authorization"] = result["authToken"].ToString();
                }
                else
                {
                    this.Header.Add("Cookie", token);
                    //this.Header.Add("Authorization", result["authToken"].ToString());
                }
            }
            else
            {
                throw new Exception($"获取MES认证失败 {result["message"]}");
            }
        }

        public string GetOAToken()
        {
            JsonConfig config = new JsonConfig();
            HttpHelper httpHelper = new HttpHelper();
            httpHelper.URL = config.SelectToken("OA.URL") + "/papi/openapi/oauth2/authorize";
            var body = new
            {
                corpid = config.SelectToken("OA.corpid"),
                response_type = "code",
                state = ""
            };
            httpHelper.Content = JsonConvert.SerializeObject(body);
            var result = JObject.Parse(httpHelper.HttpPosts());
            if (!string.IsNullOrEmpty(result["code"]?.ToString()))
            {
                HttpHelper httpHelper2 = new HttpHelper();
                httpHelper2.URL = config.SelectToken("OA.URL") + "/papi/openapi/oauth2/access_token";
                var body2 = new
                {
                    app_key = config.SelectToken("OA.app_key"),
                    app_secret = config.SelectToken("OA.app_secret"),
                    grant_type = "authorization_code",
                    code = result["code"].ToString()
                };
                httpHelper2.Content = JsonConvert.SerializeObject(body2);
                httpHelper2.ContentType = "application/x-www-form-urlencoded";
                var result2 = JObject.Parse(httpHelper2.HttpPosts());
                if (!string.IsNullOrEmpty(result2["accessToken"]?.ToString()))
                {
                    return result2["accessToken"].ToString();
                }
                else
                {
                    throw new Exception($"获取OA认证失败 {result["errmsg"]}");
                }
            }
            else
            {
                throw new Exception($"获取OA认证失败 {result["errmsg"]}");
            }
        }

        public KeyValuePair<string,string> GetOAUserInfo(string token,string usercode)
        {
            JsonConfig config = new JsonConfig();
            HttpHelper httpHelper = new HttpHelper();
            httpHelper.URL = config.SelectToken("OA.URL") + "/papi/openapi/api/hrm/restful/queryEmployee";
            var body = new OAUserDTO
            {
                access_token = token,
                jobNumList = new List<string> { usercode }
            };
            httpHelper.Content = JsonConvert.SerializeObject(body);
            var result = JObject.Parse(httpHelper.HttpPosts());
            if (!string.IsNullOrEmpty(result["data"].ToString())&& result["data"]["data"].ToArray().Count()>0)
            {

                return new KeyValuePair<string, string>(result["data"]["data"][0]["id"].ToString(), result["data"]["data"][0]["department"].ToString());
            }
            else
            {
                throw new Exception($"获取OA用户信息失败 {result["errmsg"]}");
            }
        }
    }
}
